<template>
  <div style="width: 100%">
    <el-tree
      ref="folderTreeRef"
      key="note"
      :data="noteData"
      :props="defaultProps"
      @node-click="handleNodeClick"
      :default-expand-all="isExpandAll"
      :expand-on-click-node="false"
      node-key="id"
      @node-contextmenu="handleContextmenu"
      @node-expand="openTreeNode"
      @node-collapse="closeTreeNode"
      highlight-current
      style="width: 100%"
    >
      <template #default="{ node, data }" :key="data.id">
        <div class="custom-tree-node" :key="data.id">
          <div
            style="display: flex; width: 100%; align-items: center; gap: 2px"
          >
            <el-icon
              v-if="data.icon && node.level !== 1"
              :class="[
                data.icon === 'Document' ? 'doc-theme-color' : '',
                data.icon === 'Xmind' ? 'xmind-theme-color' : '',
                data.icon === 'FlowChart' ? 'flow-chart-color' : '',
              ]"
            >
              <Component :is="MapComponent[data.icon]"></Component>
            </el-icon>
            <el-icon
              color="#f8b83f"
              v-if="data.type === 1 && node.expanded"
              size="16"
            >
              <FolderOpened />
            </el-icon>
            <el-icon
              color="#f8b83f"
              v-else-if="data.type === 1 && !node.expanded"
              ><Folder
            /></el-icon>
            <!-- <span style="padding-right: 10px"> {{ node.label }}</span> -->
            <el-text style="padding-right: 10px; width: 80%" truncated>
              {{ node.label }}
            </el-text>
          </div>
          <div v-if="node.level === 1">
            <el-icon @click="handleAppendFile($event, data)"><Plus /></el-icon>
          </div>
        </div>
      </template>
    </el-tree>
    <div v-show="showFolderMenu" class="treeMenu">
      <div class="btns-wrapper" style="position: relative; display: flex">
        <div class="child-menu1">
          <el-button
            v-for="(button, index) in moreFilledButtons"
            :key="index"
            style="
              margin: 0 !important;
              border: none !important;
              justify-content: flex-start;
            "
            :class="{ hoverActive: currentBtn === button.id }"
            @mouseenter="handleMouseEnter(button)"
            @click="handleMoreFilledClick($event, button)"
          >
            <div class="flex-between" style="width: 100px">
              <span>{{ button.label }}</span>
              <el-icon v-show="button.id === '1'"><CaretRight /></el-icon>
            </div>
          </el-button>
        </div>
        <div v-show="currentBtn === '1'" class="child-menu2">
          <div style="display: flex; flex-direction: column">
            <el-button
              v-for="(button, n) in createList"
              :key="n"
              style="
                margin: 0 !important;
                border: none !important;
                justify-content: flex-start;
              "
              @click="handleCreateFile(button)"
            >
              {{ button.label }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      draggable
      overflow
      :title="`${isEdit ? '重命名' : '新建'}${
        appendParentData && appendParentData.type === 1 ? '文件夹' : '笔记'
      }`"
      width="500"
      destroy-on-close
      @close="resetForm(ruleFormRef)"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="fileForm"
        label-width="auto"
        label-position="top"
        size="default"
        :rules="rules"
        @submit.native.prevent
        @keyup.enter.native="submitForm(ruleFormRef)"
      >
        <el-form-item label="文件夹名称" prop="name">
          <el-input
            v-model="fileForm.name"
            placeholder="最少1个字符,最长名称为8个字符"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          <el-button
            type="primary"
            :loading="modifyFileLoading"
            @click="submitForm(ruleFormRef)"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="deleteFile"
      width="400"
      :show-close="false"
      destroy-on-close
      top="30vh"
    >
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <h3
            :id="titleId"
            :class="titleClass"
            style="display: flex; align-items: center; gap: 4px"
          >
            <el-icon color="#f5922f"><WarningFilled /></el-icon> 确认删除？
          </h3>
          <p style="color: #7c8599; margin-top: 8px">
            删除内容将进入回收站，30天后自动彻底删除。
          </p>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteFile = false">取消</el-button>
          <el-button type="primary" @click="deleteNoteConfirm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 移动操作 -->
    <el-dialog
      v-model="moveFolderVisible"
      width="600"
      top="10vh"
      title="移动到"
      draggable
    >
      <p style="display: flex; align-items: center">
        <el-icon color="#f8b83f" size="24"><FolderOpened /></el-icon>
        {{ appendParentData && appendParentData.label }}
      </p>
      <div style="display: flex; align-items: center; padding: 10px 0">
        <span> 移动到：</span>
        <el-input style="flex: 1" v-model="movePath" disabled></el-input>
      </div>
      <div class="folder-wrapper">
        <el-tree
          style="max-width: 600px"
          :data="folderData"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @node-click="handleAddToFolder"
          ref="moveTreeRef"
        >
          <template #default="{ node }">
            <span
              class="custom-tree-nodex"
              style="display: flex; align-items: center"
            >
              <el-icon color="#f8b83f" size="24"><FolderOpened /></el-icon>
              <span>{{ node.label }}</span>
            </span>
          </template>
        </el-tree>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="moveFolderVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmMoveFolder">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, watch, reactive, computed, nextTick, inject } from 'vue'
import { flatTree, addLabel } from '@/utils/tools.ts'
import { useRouter, useRoute } from 'vue-router'
import {
  httpCreatefolder,
  httpUpdatefolder,
  httpCreateNote,
  httpDeletefolder,
  httpMovefolder,
  httpDeleteNoteBook,
  httpAddShortCut,
} from '@/api/note'
import { ElMessage } from 'element-plus'
import Xmind from '@/icons/Xmind.vue'
import FlowChart from '@/icons/FlowChart.vue'
import useNoteStore from '@/stores/note'
import { storeToRefs } from 'pinia'
import {
  Document,
  FolderOpened,
  WarningFilled,
  CaretRight,
  Plus,
} from '@element-plus/icons-vue'
const noteState = useNoteStore()
const { selectedFolder, selectedTag, noteData, shortCutData } =
  storeToRefs(noteState)
noteState.getFolderListData()
const folderTreeRef = ref()
const MapFeat = [
  {
    id: 1,
    label: '文件夹',
  },
  {
    id: 2,
    label: '笔记',
  },
  {
    id: 3,
    label: '脑图',
  },
  {
    id: 4,
    label: '流程图',
  },
]
const createList = computed(() => {
  if (appendParentData.value.level <= 8) {
    return MapFeat
  } else {
    return MapFeat.slice(1)
  }
})
const MapComponent = {
  FlowChart,
  Xmind,
  Document,
}
const movePath = ref('')
const router = useRouter()
const route = useRoute()
const deleteFile = ref(false)
const ruleFormRef = ref()
const isExpandAll = ref(true)
const dialogVisible = ref(false)
const isEdit = ref(false)
const showFolderMenu = ref(false)
// const selectedNote = ref()
const folderData = ref() // 移动的文件夹树形结构
const moveTreeRef = ref()
const modifyFileLoading = ref(false)
const appendParentData = ref({}) // 右击选择的数据
let staticList = [
  {
    id: '1',
    label: '新建',
  },
  {
    id: '2',
    label: '重命名',
  },
  {
    id: '3',
    label: '删除',
  },
  {
    id: '4',
    label: '添加到文件夹',
  },
  {
    id: '5',
    label: '添加到快捷方式',
  },
]
const moveFolderVisible = ref(false) // 移动文件夹或者笔记的弹窗
const fileForm = reactive({
  name: '',
})
const model = defineModel()
const parentTreeWrapper = inject('operationDom') // 注入
const closeShortCut = inject('closeShortCut')
// 1.文件夹 笔记  脑图 流程图
let iconMap = {
  2: 'Document',
  3: 'Xmind',
  4: 'FlowChart',
}
let pathMap = {
  2: '/file/doc/',
  3: '/file/mindmap/',
  4: '/file/drawio/',
}

const moreFilledButtons = computed(() => {
  if (appendParentData.value && appendParentData.value.type === 2) {
    return staticList.slice(1)
  } else {
    return staticList
  }
})
// 去除自己文件夹和笔记
function handleToTree(data) {
  let arr = []
  data.forEach((item) => {
    if (item.id !== appendParentData.value.id) {
      if (item.children) {
        item.children = handleToTree(item.children)
        arr.push(item)
      } else {
        // 文件夹
        item.type === 1 && arr.push(item)
      }
    }
  })
  return arr
}

watch(
  () => appendParentData.value,
  () => {
    folderData.value = handleToTree(JSON.parse(JSON.stringify(noteData.value)))
    addLabel(folderData.value)
  },
  {
    deep: true,
  },
)
watch(
  () => showFolderMenu.value,
  () => {
    if (showFolderMenu.value) {
      nextTick(() => {
        parentTreeWrapper.value.style.overflow = 'hidden'
      })
    } else {
      nextTick(() => {
        parentTreeWrapper.value.style.overflow = 'auto'
      })
    }
  },
)
const validateFileName = (rule, value, callback) => {
  let flag
  if (!isEdit.value) {
    flag = appendParentData.value.children?.find((item) => {
      return item.label === value && item.type === appendParentData.value.type
    })
  } else {
    const flatTreeData = flatTree(noteData.value)
    // 相同pid 相同type
    let arr = flatTreeData.filter((item) => {
      return (
        item.pid === appendParentData.value.pid &&
        item.type === appendParentData.value.type
      )
    })
    flag = arr.some((item) => {
      return (
        item.label === value &&
        item.id !== appendParentData.value.id &&
        item.type === appendParentData.value.type
      )
    })
  }
  if (value === '') {
    callback(new Error('请输入笔记文件名称'))
  } else if (flag) {
    callback(new Error('同级文件夹下不能有重名的文件'))
  } else {
    callback()
  }
}
const rules = {
  name: [
    {
      required: true,
      message: '请输入笔记文件名称',
      trigger: ['blur', 'change'],
    },
    {
      validator: validateFileName,
    },
  ],
}
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      modifyFileLoading.value = true
      if (isEdit.value) {
        const res = await httpUpdatefolder({
          folder_id: appendParentData.value.id,
          name: fileForm.name,
        })
        if (res) {
          ElMessage.success('修改成功')
          await noteState.getFolderListData()
        } else {
          ElMessage.error('修改失败')
        }
        // TODO: 调用修改接口 修改的时候要判断  在当前文件夹中 修改的文件名称不能和其他文件一致
      } else {
        // TODO: 调用新增接口
        const res = await httpCreatefolder({
          parent_id: appendParentData.value && appendParentData.value.id,
          name: fileForm.name,
        })
        if (res) {
          ElMessage.success('创建成功')
          await noteState.getFolderListData()
        } else {
          ElMessage.error('创建失败')
        }
      }
      modifyFileLoading.value = false
      dialogVisible.value = false
      formEl.resetFields()
      await noteState.getShortCutList()
    } else {
      console.log('error submit!', fields)
    }
  })
}
const handleContextmenu = (e, data, node) => {
  emit('hide') // || data.type === 2
  closeShortCut()
  if (node.level === 1) {
    showFolderMenu.value = false
    return
  }
  appendParentData.value = data
  e.preventDefault()
  showFolderMenu.value = true // 显示菜单
  const mouseY = event.clientY // 获取鼠标右击事件的垂直坐标
  const viewportHeight = window.innerHeight // 获取视口的高度
  const distanceToBottom = viewportHeight - mouseY // 计算距离视口底部的距离
  if (distanceToBottom < 150) {
    document
      .querySelector('.treeMenu')
      .setAttribute(
        'style',
        `top:${e.clientY - 100}px;left:${e.clientX + 10}px;`,
      )
  } else {
    document
      .querySelector('.treeMenu')
      .setAttribute('style', `top:${e.clientY}px;left:${e.clientX + 10}px;`)
  }
  document.addEventListener('click', closePopOver)
  document.addEventListener('contextmenu', closePopOver)
}
const openTreeNode = () => {
  showFolderMenu.value = false
  closeShortCut()
  emit('hide')
}
const closeTreeNode = () => {
  showFolderMenu.value = false
  closeShortCut()
  emit('hide')
}
const closePopOver = () => {
  showFolderMenu.value = false
}
const resetForm = (formEl) => {
  if (!formEl) return
  dialogVisible.value = false
  formEl.resetFields()
  fileForm.name = ''
}
const deleteNoteConfirm = async () => {
  let res
  if (appendParentData.value.type === 1) {
    res = await httpDeletefolder({
      folder_id: appendParentData.value.id,
    })
  } else {
    res = await httpDeleteNoteBook({
      detail_id: appendParentData.value.id,
    })
  }
  // 如果当前文件夹被删除，则跳转到全部文件夹
  if (
    selectedFolder.value.id &&
    appendParentData.value.childIds.length &&
    appendParentData.value.childIds.includes(selectedFolder.value.id)
  ) {
    selectedFolder.value = noteData.value[0]
    router.push('/file/note')
  }
  if (!selectedFolder.value.id) {
    selectedFolder.value = noteData.value[0]
    router.push('/file/note')
  }
  if (res) {
    ElMessage.success('删除成功')
    await noteState.getFolderListData()
    noteState.getShortCutList()
    // noteState.getList()
    folderTreeRef.value.setCurrentKey(selectedFolder.value.id)
  } else {
    ElMessage.error('删除失败')
  }
  deleteFile.value = false
}
watch(
  () => [route.params, noteData.value],
  () => {
    nextTick(() => {
      if (route.params) {
        let id = Object.values(route.params)[0]
        if (Array.isArray(id)) {
          folderTreeRef.value.setCurrentKey(id[0])
        } else {
          // fix: bug
          // folderTreeRef.value.setCurrentKey(selectedFolder.value.id)
          folderTreeRef.value.setCurrentKey(id || noteData.value[0].id)
        }
      } else {
        if (selectedFolder.value.id) {
          folderTreeRef.value.setCurrentKey(selectedFolder.value.id)
        }
      }
    })
  },
  { deep: true, immediate: true },
)
const currentBtn = ref('')
const handleMouseEnter = (item) => {
  currentBtn.value = item.id
}

const handleCreateFile = async (item) => {
  if (item.id === 1) {
    dialogVisible.value = true
  } else {
    const res = await httpCreateNote({
      folder_id: appendParentData.value.id || 0,
      title: '',
      content: '',
      icon: iconMap[item.id],
      label_id_list: [],
    })
    if (res) {
      ElMessage.success('创建成功')
      await noteState.getFolderListData()
      await noteState.getShortCutList()
      folderTreeRef.value.setCurrentKey(res.id)
      selectedFolder.value = { id: res.id }
      router.push(pathMap[item.id] + res.id)
    }
  }
}
const handleMoreFilledClick = async (e, button) => {
  e.stopPropagation()
  e.preventDefault()
  if (button.id === '1') {
    // 1.新建
    // dialogVisible.value = true
  } else if (button.id === '2') {
    // 2.重命名
    fileForm.name = appendParentData.value.label
    dialogVisible.value = true
    isEdit.value = true
  } else if (button.id === '3') {
    // 3. 删除
    deleteFile.value = true
  } else if (button.id === '4') {
    // 4.添加到文件夹
    moveFolderVisible.value = true
    await nextTick(() => {
      moveTreeRef.value.setCurrentKey(1) // 默认是全部文件夹
      targetFolderData.value = noteData.value[0]
      movePath.value = noteData.value[0].label
    })
  } else {
    // 5.添加到快捷方式 1文件夹，2为笔记，3为标签
    showFolderMenu.value = false
    let flag = shortCutData.value && shortCutData.value[0].children
    if (flag.length && flag.some((x) => x.id === appendParentData.value.id)) {
      return ElMessage.error('快捷方式已存在')
    }
    const res = await httpAddShortCut({
      shortcut_id: appendParentData.value.id,
      shortcut_type: appendParentData.value.type,
    })
    if (res) {
      ElMessage.success('添加成功')
      await noteState.getShortCutList()
    }
  }
}
const handleAppendFile = (e, data, node) => {
  // console.log('data', data, node)

  showFolderMenu.value = false
  emit('hide')
  closeShortCut()
  e.stopPropagation()
  isEdit.value = false
  dialogVisible.value = true
  appendParentData.value = data
  appendParentData.value.id = 0
}
const MapJump = {
  Document: (id) => {
    router.push(`/file/doc/${id}`)
  },
  Xmind: (id) => {
    router.push(`/file/mindmap/${id}`)
  },
  FlowChart: (id) => {
    router.push(`/file/drawio/${id}`)
  },
}
const handleNodeClick = (data) => {
  emit('clearHighLight')
  closeShortCut()
  showFolderMenu.value = false
  emit('hide')
  // selectedNote.value = data
  if (data.type === 1) {
    model.value = data
    selectedTag.value = ''
    router.push('/file/note')
  } else {
    model.value = data
    selectedTag.value = ''
    MapJump[data.icon](data.id)
  }
}

const targetFolderData = ref()
const handleAddToFolder = (data) => {
  targetFolderData.value = data
  movePath.value = data.path
}
const confirmMoveFolder = async () => {
  if (
    appendParentData.value.deepLevel -
      appendParentData.value.level +
      targetFolderData.value.level >
    9
  ) {
    ElMessage({
      message: '文件夹层级不能超过9层',
      type: 'warning',
    })
    return
  }
  if (
    appendParentData.value.type === 1 &&
    targetFolderData.value.children &&
    targetFolderData.value.children.some(
      (x) => x.label === appendParentData.value.label,
    )
  ) {
    ElMessage({
      message: '文件夹中已存在该文件',
      type: 'warning',
    })
    return
  } else {
    // 移动笔记
    const flatTreeData = flatTree(noteData.value)
    let target = flatTreeData.find((x) => x.id === targetFolderData.value.id)
    let flag =
      target.children &&
      target.children.some(
        (item) =>
          item.type === appendParentData.value.type &&
          item.label === appendParentData.value.label,
      )
    if (target && flag) {
      return ElMessage({
        message: '相同笔记名称已存在该文件',
        type: 'warning',
      })
    }
  }
  const res = await httpMovefolder({
    folder_id: appendParentData.value.id,
    parent_id: targetFolderData.value.id,
  })
  if (res) {
    ElMessage({
      message: '文件夹中移动成功',
      type: 'success',
    })
    moveFolderVisible.value = false
    await noteState.getFolderListData()
    await noteState.getShortCutList()
  }
}

const defaultProps = {
  children: 'children',
  label: 'label',
}
const emit = defineEmits(['hide', 'clearHighLight'])
function setFolderTreeRefKey(value) {
  folderTreeRef.value.setCurrentKey(value)
  // const node = noteTreeRef.value.getCurrentNode()
}
defineExpose({
  closePopOver,
  setFolderTreeRefKey,
})
</script>
<style scoped lang="scss">
.flex-between {
  display: flex;
  justify-content: space-between;
}
.hoverActive {
  background-color: var(--el-button-hover-bg-color);
  color: var(--el-button-hover-text-color);
  outline: none;
}
.custom-tree-node {
  width: 100%;
  display: flex;
  gap: 14px;
  align-items: center;
  // justify-content: space-between;
}
.treeMenu {
  font-size: 14px;
  position: fixed;
  z-index: 999;
  top: 50%;
  left: 50%;
  background-color: #fff;
  border-radius: 5px;
  .child-menu1 {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 100%;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  }
  .child-menu2 {
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  }
}
.folder-wrapper {
  height: 300px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-sizing: border-box;
}
</style>
